from easycore.common.registry import Registry


class TransformLoader:
    registry = Registry("transform")
    reusable_transform_pool = {}

    @classmethod
    def register(cls, transform_type_name=None, obj=None):
        return cls.registry.register(transform_type_name, obj)

    @classmethod
    def get(cls, *transform_configs):
        if len(transform_configs) == 1:
            transform_config = transform_configs
        else:
            transform_config = {
                "type": "Compose",
                "transforms": transform_configs,
            }

        transform_id = cls.hash_transform_config(transform_config)
        if transform_id in cls.reusable_transform_pool:
            transform = cls.reusable_transform_pool[transform_id]
        else:
            transform = cls.registry.get(transform_config['type'])(transform_config)
            cls.reusable_transform_pool[transform_id] = transform

        return transform

    @classmethod
    def hash_transform_config(cls, transform_config):
        return hash(str(transform_config))
